<template>
  <div class="home-container">
    <!-- 工具栏区域 -->
    <el-row :gutter="20" class="toolbar">
      <el-col :span="6">
        <el-select 
          v-model="selectedCategory" 
          placeholder="选择分类" 
          clearable 
          @change="fetchProducts"
          :loading="categoryLoading">
          <el-option
            v-for="item in categories"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </el-col>
    </el-row>

    <!-- 商品列表区域（可滚动） -->
    <div class="product-list-container">
      <el-row :gutter="20" class="product-list">
        <el-col :span="6" class="product-col" v-for="product in products" :key="product.id">
          <el-card :body-style="{ padding: '0px' }" class="product-card">
            <img :src="product.image" class="product-image">
            <div class="product-info">
              <h3>{{ product.name }}</h3>
              <div class="price-info">
                <span class="price">¥{{ product.price }}</span>
                <span class="original-price">¥{{ product.originalPrice }}</span>
              </div>
              <div class="group-info">
                <span>已团{{ product.groupCount }}件</span>
                <span>剩余{{ product.stock }}件</span>
              </div>
              <div class="action-buttons">
                <el-button type="primary" @click="handleViewDetail(product.id)">查看详情</el-button>
                <el-button @click="handleAddToCart(product)">加入购物车</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <div v-if="loading" class="loading-container">
        <el-loading :fullscreen="false" />
      </div>

      <div v-if="!loading && products.length === 0" class="empty-container">
        <el-empty description="暂无商品" />
      </div>
    </div>
  </div>
  
  <!-- 改为独立的分页区域，不受容器影响 -->
  <div class="pagination-wrapper">
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElLoading } from 'element-plus'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const selectedCategory = ref('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const products = ref([])
const loading = ref(false)
const categoryLoading = ref(false)

// 分类数据从后端获取
const categories = ref([])

// 获取分类数据
const fetchCategories = async () => {
  try {
    categoryLoading.value = true
    
    // 调用后端API
    const response = await fetch('/api/categories')
    
    if (!response.ok) {
      throw new Error('获取分类列表失败')
    }
    
    const data = await response.json()
    
    if (data.code !== 200) {
      throw new Error(data.message || '获取分类列表失败')
    }
    
    // 转换格式为下拉框需要的格式
    categories.value = (data.data || []).map(category => ({
      value: category.id.toString(),
      label: category.name
    }))
    
    // 如果没有分类，显示提示
    if (categories.value.length === 0) {
      categories.value = [{
        value: '',
        label: '暂无分类数据'
      }]
    }
    
    console.log('前台页面加载的分类数据:', categories.value)
  } catch (error) {
    console.error('获取分类列表错误:', error)
    // 加载失败时添加一个默认选项
    categories.value = [{
      value: '',
      label: '加载分类失败'
    }]
  } finally {
    categoryLoading.value = false
  }
}

// 获取商品列表数据
const fetchProducts = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = new URLSearchParams()
    if (searchKeyword.value) {
      params.append('name', searchKeyword.value)
    }
    if (selectedCategory.value) {
      params.append('categoryId', selectedCategory.value)
    }
    params.append('pageNum', currentPage.value)
    params.append('pageSize', pageSize.value)
    
    // 调用后端API
    const response = await fetch(`/api/products?${params.toString()}`)
    
    if (!response.ok) {
      throw new Error('获取商品列表失败')
    }
    
    const responseText = await response.text()
    let data
    
    try {
      data = JSON.parse(responseText)
    } catch (e) {
      console.error('解析响应JSON失败:', e)
      throw new Error('服务器返回的数据格式不正确')
    }
    
    if (data.code !== 200) {
      throw new Error(data.message || '获取商品列表失败')
    }
    
    // 更新商品列表数据，匹配后端返回的新结构
    products.value = data.data?.data || []
    total.value = data.data?.total || 0
    
  } catch (error) {
    console.error('获取商品列表错误:', error)
    ElMessage.error(error.message || '获取商品列表失败，请稍后再试')
    products.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置为第一页
  fetchProducts()
}

const handleViewDetail = (id) => {
  router.push(`/product/${id}`)
}

// 获取认证头信息
const getAuthHeaders = () => {
  const token = localStorage.getItem('token')
  return {
    'Content-Type': 'application/json',
    'Authorization': token ? `Bearer ${token}` : ''
  }
}

const handleAddToCart = async (product) => {
  try {
    // 构建请求数据
    const cartData = {
      productId: product.id,
      quantity: 1 // 默认添加一件商品
    }
    
    // 调用后端API
    const response = await fetch('/api/cart/items', {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify(cartData)
    })
    
    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.message || '添加到购物车失败')
    }
    
    const result = await response.json()
    
    if (result.code !== 200) {
      throw new Error(result.message || '添加到购物车失败')
    }
    
    ElMessage.success('已成功加入购物车')
  } catch (error) {
    console.error('添加购物车错误:', error)
    ElMessage.error(error.message || '添加到购物车失败，请稍后再试')
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchProducts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProducts()
}

// 页面加载时获取商品列表
onMounted(() => {
  fetchCategories() // 先获取分类数据
  fetchProducts()
})
</script>

<style scoped>
.home-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 65px); /* 减去分页器的高度 */
  background-color: #f5f7fa;
  overflow: hidden;
  position: relative; /* 确保相对定位 */
}

.toolbar {
  padding: 15px;
  background-color: white;
  margin-bottom: 0;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  z-index: 2; /* 降低z-index确保不会遮挡顶部导航下拉菜单 */
  flex-shrink: 0;
}

.product-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.product-list {
  margin-bottom: 20px;
}

.product-col {
  margin-bottom: 20px;
}

.product-card {
  height: 100%;
  transition: all 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px 4px 0 0;
}

.product-info {
  padding: 14px;
}

.product-info h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.price-info {
  margin: 10px 0;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 14px;
}

.group-info {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: space-between;
  margin-top: 10px;
}

/* 新的分页器样式 */
.pagination-wrapper {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 3; /* 降低z-index确保不会遮挡顶部导航下拉菜单 */
}

.pagination-container {
  height: 65px;
  padding: 15px;
  background-color: white;
  box-shadow: 0 -2px 8px rgba(0,0,0,0.15);
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.empty-container {
  background-color: white;
  padding: 40px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .home-container {
    height: calc(100vh - 55px); /* 移动端减少分页器高度 */
  }

  .toolbar {
    padding: 10px;
  }
  
  .product-list-container {
    padding: 10px;
  }
  
  .pagination-container {
    padding: 10px;
    height: 55px; /* 移动端减少高度 */
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .empty-container {
    padding: 20px;
  }
}
</style>

<!-- 添加全局样式，不使用scoped -->
<style>
/* 修复分类下拉列表样式 - 使用更精确的选择器 */
body .el-popper.is-light {
  background-color: white !important;
  border: 1px solid #e4e7ed !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.15) !important;
  z-index: 3000 !important;
}

.el-select-dropdown {
  background-color: white !important;
  border: 1px solid #e4e7ed !important;
}

.el-select-dropdown__wrap {
  max-height: 274px;
  margin-bottom: 0 !important;
  overflow: auto;
  background-color: white !important;
}

.el-select-dropdown__list {
  padding: 6px 0 !important;
  margin: 0 !important;
  box-sizing: border-box;
  background-color: white !important;
}

.el-select-dropdown__item {
  font-size: 14px;
  padding: 0 20px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  height: 34px;
  line-height: 34px;
  box-sizing: border-box;
  cursor: pointer;
  background-color: white !important;
}

.el-select-dropdown__item.selected,
.el-select-dropdown__item.hover,
.el-select-dropdown__item:hover {
  background-color: #f5f7fa !important;
  color: #409eff !important;
}

/* 确保箭头也有背景色 */
.el-popper__arrow::before {
  background-color: white !important;
  border-color: #e4e7ed !important;
}
</style>
